#include "spi.h"
#include "lpc17xx_gpio.h"
#include "lpc17xx_pinsel.h"

SPI_DATA_SETUP_Type spiDataBuf;


/*********************************************************************/
void SPI_CS_Force(int32_t state)
{
		if (state){
						GPIO_SetValue(SPI_CS_PORT_NUM, (1<<SPI_CS_PIN_NUM));
		}else{
						GPIO_ClearValue(SPI_CS_PORT_NUM, (1<<SPI_CS_PIN_NUM));
		}
}

/*********************************************************************/
void SPI_CS_Init(void)
{
		GPIO_SetDir(SPI_CS_PORT_NUM, (1<<SPI_CS_PIN_NUM), 1);
		GPIO_SetValue(SPI_CS_PORT_NUM, (1<<SPI_CS_PIN_NUM));
}

void SPIInit()
{
	SPI_CFG_Type SPI_ConfigStruct;
	PINSEL_CFG_Type PinCfg;
		/*
	 * Initialize SPI pin connect
	 * P0.15 - SCK;
	 * P0.16 - SSEL - used as GPIO
	 * P0.17 - MISO
	 * P0.18 - MOSI
	 */
	PinCfg.Funcnum = 3;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Portnum = 0;
	PinCfg.Pinnum = 15;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 17;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 18;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 16;
	PinCfg.Funcnum = 0;
	PINSEL_ConfigPin(&PinCfg);

	SPI_ConfigStruct.CPHA = SPI_CPHA_FIRST;
	SPI_ConfigStruct.CPOL = SPI_CPOL_HI;
	SPI_ConfigStruct.ClockRate = 5000000;
	SPI_ConfigStruct.DataOrder = SPI_DATA_MSB_FIRST;
	SPI_ConfigStruct.Databit = SPI_DATABIT_8;
	SPI_ConfigStruct.Mode = SPI_MASTER_MODE;

	//SPI_ConfigStructInit(&SPI_ConfigStruct);
	// Initialize SPI peripheral with parameter given in structure above
	SPI_Init(LPC_SPI, &SPI_ConfigStruct);
	SPI_CS_Init();
}